package com.alan.netty.nio.channels;

import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;

/**
 * @author weiBin
 * @date 2018/11/7
 */
public class DatagramChannelSend {
    public static void main(String[] args) throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.configureBlocking(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                byte[] bytes;
                while (true) {
                    buffer.clear();
                    SocketAddress socketAddress = null;
                    try {
                        socketAddress = datagramChannel.receive(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (socketAddress != null) {
                        buffer.rewind();
                        bytes = new byte[buffer.limit()];
                        buffer.get(bytes);
                        try {
                            System.out.println("receive remote " + socketAddress.toString() + ":" + new String(bytes, "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        //发送控制台输入消息
        System.out.println("请输入发送至服务器的内容：");
        while (true) {
            Scanner sc = new Scanner(System.in);
            String next = sc.next();
            try {
                sendMessage(datagramChannel, next);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void sendMessage(DatagramChannel datagramChannel, String msg) throws IOException {
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        System.out.println("send msg:" + msg);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        buffer.put(msg.getBytes("UTF-8"));
        buffer.flip();
        datagramChannel.send(buffer, new InetSocketAddress("127.0.0.1", 1234));
    }
}
